package edu.dlust.trading_platform;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import edu.dlust.trading_platform.DataBase.MySQL;
import edu.dlust.trading_platform.DataBase.Redis;
import edu.dlust.trading_platform.ability.SendMail;
import edu.dlust.trading_platform.DataBean.random;

public class RegisterActivity extends AppCompatActivity {
    private EditText username,phone,uid,passwd,repasswd,email,check;
    private Button getmail,register,login;
    boolean waits = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        register();
        getcode();
        login();
    }
    private void register(){
        username = findViewById(R.id.usernameEditText);
        phone = findViewById(R.id.phoneNumberEditText);
        uid = findViewById(R.id.studentIdEditText);
        passwd = findViewById(R.id.passwordEditText);
        repasswd = findViewById(R.id.repeatPasswordEditText);
        email = findViewById(R.id.emailVerificationCodeEditText);
        check = findViewById(R.id.emailEditText);

        register = findViewById(R.id.registerButton);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uname = username.getText().toString();
                String pnumber = phone.getText().toString();
                String uuid = uid.getText().toString();
                String pswd = passwd.getText().toString();
                String rpswd = repasswd.getText().toString();
                String mail = email.getText().toString();
                String chek = check.getText().toString();

                if (uname.equals("") || pnumber.equals("") || uuid.equals("") || pswd.equals("") || rpswd.equals("") || mail.equals("") || chek.equals("")){
                    Toast.makeText(RegisterActivity.this, "请完整填写以上信息", Toast.LENGTH_SHORT).show();
                    return;
                }else if (pnumber.length() <= 10 || pnumber.length() >=12){
                    Toast.makeText(RegisterActivity.this, "请正确填写手机号", Toast.LENGTH_SHORT).show();
                    return;
                }else if (uuid.length() <=9 || uuid.length() >= 11){
                    Toast.makeText(RegisterActivity.this, "请正确填写学号", Toast.LENGTH_SHORT).show();
                    return;
                }else if (!pswd.equals(rpswd)){
                    Toast.makeText(RegisterActivity.this, "两次密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }else if(!CheckCode(mail,Integer.parseInt(chek))){
                    Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                    return;
                }else if(CheckUid(uuid)){
                    Toast.makeText(RegisterActivity.this, "该学号已被注册", Toast.LENGTH_SHORT).show();
                }else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String sql = "INSERT INTO LOGINID(Uid,Pswd,UName,Mail,Phone) VALUES(?,?,?,?,?);";
                            Connection con = MySQL.getConnection();
                            try {
                                PreparedStatement ps = con.prepareStatement(sql);
                                ps.setString(1, uuid);
                                ps.setString(2, pswd);
                                ps.setString(3, uname);
                                ps.setString(4, mail);
                                ps.setString(5, pnumber);
                                int as =0;
                                as = ps.executeUpdate();
                                if (as>=1){
                                    con.close();
                                    as = 0;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(RegisterActivity.this, "注册成功!", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    Intent intent = new Intent();
                                    intent.putExtra("uid",uuid);
                                    setResult(1,intent);
                                    RegisterActivity.this.finish();
                                }else {
                                    con.close();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(RegisterActivity.this, "注册失败!", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();
                }
            }
        });
    }

    private void getcode(){
        getmail = findViewById(R.id.getEmailVerificationCodeButton);
        email = findViewById(R.id.emailVerificationCodeEditText);

        getmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String mail = email.getText().toString();
                if(waits){
                if (mail.length() == 0) {
                    Toast.makeText(RegisterActivity.this, "请正确填写邮箱", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            random random = new random();
                            Redis redis = new Redis();
                            int code = random.create();
                            SendMail sendMailTask = new SendMail(mail, code);
                            redis.create(mail,code);
                            sendMailTask.execute();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(RegisterActivity.this, "已成功发送验证码", Toast.LENGTH_SHORT).show();
                                    waits = false;
                                    waiting();
                                }
                            });
                        }
                    }).start();
                }
            }else {
                    Toast.makeText(RegisterActivity.this, "请等待60秒后再申请,重复申请仅生效最新验证码！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void waiting() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                waits = true;
                timer.cancel(); // 取消定时任务
            }
        }, 60000); // 60秒等待时间，1秒 = 1000毫秒
    }

    public boolean CheckCode(String mail, int check) {
        FutureTask<Boolean> futureTask = new FutureTask<>(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                Redis redis = new Redis();
                int result = Integer.parseInt(redis.find(mail));
                return result == check;
            }
        });
        new Thread(futureTask).start();
        try {
            return futureTask.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean CheckUid(String uid){
        FutureTask<Boolean> futureTask = new FutureTask<>(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                String strsql = "SELECT * FROM LOGINID WHERE Uid = ?";
                Connection con = MySQL.getConnection();
                PreparedStatement ps = con.prepareStatement(strsql);
                ps.setString(1, uid);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    con.close();
                    return true;
                }else {
                    con.close();
                    return false;
                }
            }
        });
        new Thread(futureTask).start();
        try {
            return futureTask.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void login(){
        login = findViewById(R.id.loginButton);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                startActivity(intent);
                RegisterActivity.this.finish();
            }
        });
    }
}